#include "stdafx.h"
#include "Link.h"

Link::Link(void){
	prev=this;
	next=0;
	size=0;
	data=0;
}
Link::~Link(void){
	if(data)
		free(data);
}
void Link::append(void *buffer,uint length){
	Link *p=new Link();
	if(p){
		void *d=malloc(length);
		if(d){
			memcpy(d,buffer,length);
			p->data=d;
			p->size=length;
			Link *t=prev;
			p->prev=t;
			p->next=0;
			prev=t->next=p;
			return;
		}
		delete p;
	}
	throw(0);
}
uint Link::comp(void *buf){
	if(!size){
		for(Link *p=next;p;p=p->next)
			size+=p->size;
		ubyte *d=(ubyte*)malloc(size);
		data=d;
		if(d){
			for(Link *p=next;p;){
				uint n=p->size;
				memcpy(d,p->data,n);
				Link *x=p->next;
				delete p;
				p=x;
				d+=n;
			}
			next=0;
		}else size=0;
	}
	if(buf && size)
		memcpy(buf,data,size);
	return size;
}